<template>
  <div class="map-container">
    <div id="viewDiv" class="map-view"></div>

    <!-- 属性信息弹窗 -->
    <el-dialog v-model="showAttributeDialog" title="卫生间设施详情" width="60%" destroy-on-close>
      <div v-if="selectedFeature" class="facility-details">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="名称">{{
            selectedFeature.attributes.name || '未知'
          }}</el-descriptions-item>
          <el-descriptions-item label="地址">{{
            selectedFeature.attributes.address || '未知'
          }}</el-descriptions-item>
          <el-descriptions-item label="卫生间类型">{{
            selectedFeature.attributes.BathroomType || '未知'
          }}</el-descriptions-item>
          <el-descriptions-item label="性别">{{
            selectedFeature.attributes.gender || '未知'
          }}</el-descriptions-item>
          <el-descriptions-item label="无障碍设施">{{
            selectedFeature.attributes.is_accessible || '未知'
          }}</el-descriptions-item>
          <el-descriptions-item label="是否免费">{{
            selectedFeature.attributes.is_free || '未知'
          }}</el-descriptions-item>
          <el-descriptions-item label="费用">{{
            selectedFeature.attributes.fee || '未知'
          }}</el-descriptions-item>
          <el-descriptions-item label="开放时间">{{
            selectedFeature.attributes.open_time || '未知'
          }}</el-descriptions-item>
          <el-descriptions-item label="开放日">{{
            selectedFeature.attributes.open_days || '未知'
          }}</el-descriptions-item>
          <el-descriptions-item label="厕位数量">{{
            selectedFeature.attributes.toilet_count || '未知'
          }}</el-descriptions-item>
          <el-descriptions-item label="维护电话">
            <a
              v-if="selectedFeature.attributes.MaintanceNumber"
              :href="`tel:${selectedFeature.attributes.MaintanceNumber}`"
              >{{ selectedFeature.attributes.MaintanceNumber }}</a
            >
            <span v-else>未知</span>
          </el-descriptions-item>
        </el-descriptions>
        <!-- 新增照片展示部分 -->
        <div class="section-title">
          <h3>设施照片</h3>
        </div>
        <div v-if="selectedFeature.attributes.Photo" class="facility-photo-section">
          <el-image
            :src="selectedFeature.attributes.Photo"
            :preview-src-list="[selectedFeature.attributes.Photo]"
            fit="cover"
            style="max-width: 100%; max-height: 300px"
          >
            <template #error>
              <div class="image-error">
                <el-icon><Picture /></el-icon>
                <span>图片加载失败</span>
              </div>
            </template>
          </el-image>
        </div>
        <el-empty v-else description="暂无照片" />
        <!-- 用户评论部分 -->
        <div class="section-title">
          <h3>用户评论</h3>
          <el-button
            v-if="authStore.userRole === 'guest'"
            type="primary"
            size="small"
            @click="showAddReviewDialog = true"
          >
            添加评论
          </el-button>
        </div>
        <div v-if="reviews && reviews.length > 0" class="reviews-section">
          <el-timeline>
            <el-timeline-item v-for="(review, index) in reviews" :key="index" placement="top">
              <el-card>
                <div class="review-header">
                  <span class="username">{{ review.username }}</span>
                  <el-rate :model-value="review.rating" disabled show-score text-color="#ff9900" />
                </div>
                <div class="review-content">{{ review.comment }}</div>
                <div class="review-details">
                  <el-tag size="small">清洁度: {{ review.cleanliness }}</el-tag>
                  <el-tag size="small" type="success">设施: {{ review.facility }}</el-tag>
                  <el-tag size="small" type="info">便利性: {{ review.convenience }}</el-tag>
                </div>
                <!-- 添加管理员回复显示 -->
                <div v-if="review.adminReply" class="admin-reply">
                  <div class="admin-reply-header">
                    <el-icon><ChatDotRound /></el-icon>
                    <span>管理员回复:</span>
                  </div>
                  <div class="admin-reply-content">{{ review.adminReply }}</div>
                </div>
              </el-card>
            </el-timeline-item>
          </el-timeline>
        </div>
        <el-empty v-else description="暂无评论" />

        <!-- 问题报告部分 -->
        <div class="section-title">
          <h3>问题报告</h3>
          <el-button
            v-if="authStore.userRole === 'guest'"
            type="primary"
            size="small"
            @click="showAddIssueDialog = true"
          >
            提交问题
          </el-button>
        </div>
        <div v-if="issues && issues.length > 0" class="issues-section">
          <el-table :data="issues" style="width: 100%">
            <el-table-column prop="date" label="日期" width="100" />
            <el-table-column prop="reporter_name" label="报告人" width="100" />
            <el-table-column prop="type" label="问题类型" width="120" />
            <el-table-column prop="description" label="描述" />
            <el-table-column prop="status" label="状态" width="100">
              <template #default="scope">
                <el-tag :type="scope.row.status === '已处理' ? 'success' : 'warning'">
                  {{ scope.row.status }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="priority" label="优先级" width="80">
              <template #default="scope">
                <el-tag
                  :type="
                    scope.row.priority === '高'
                      ? 'danger'
                      : scope.row.priority === '中'
                        ? 'warning'
                        : 'info'
                  "
                >
                  {{ scope.row.priority }}
                </el-tag>
              </template>
            </el-table-column>
            <!-- 添加管理员回复列 -->
            <el-table-column prop="adminReply" label="管理员回复">
              <template #default="scope">
                <span v-if="scope.row.adminReply">{{ scope.row.adminReply }}</span>
                <el-tag v-else type="info" size="small">暂无回复</el-tag>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <el-empty v-else description="暂无问题报告" />
      </div>
    </el-dialog>

    <!-- 添加评论弹窗 -->
    <el-dialog v-model="showAddReviewDialog" title="添加评论" width="50%" destroy-on-close>
      <el-form :model="reviewForm" label-width="100px" :rules="reviewRules" ref="reviewFormRef">
        <el-form-item label="总体评分" prop="rating">
          <el-rate v-model="reviewForm.rating" show-score :max="5" />
        </el-form-item>
        <el-form-item label="清洁度" prop="cleanliness">
          <el-rate v-model="reviewForm.cleanliness" show-score :max="5" />
        </el-form-item>
        <el-form-item label="设施" prop="facility">
          <el-rate v-model="reviewForm.facility" show-score :max="5" />
        </el-form-item>
        <el-form-item label="便利性" prop="convenience">
          <el-rate v-model="reviewForm.convenience" show-score :max="5" />
        </el-form-item>
        <el-form-item label="评论内容" prop="comment">
          <el-input
            v-model="reviewForm.comment"
            type="textarea"
            :rows="4"
            placeholder="请输入您的评论内容"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showAddReviewDialog = false">取消</el-button>
          <el-button type="primary" @click="submitReview" :loading="submitting">提交</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 提交问题弹窗 -->
    <el-dialog v-model="showAddIssueDialog" title="提交问题" width="50%" destroy-on-close>
      <el-form :model="issueForm" label-width="100px" :rules="issueRules" ref="issueFormRef">
        <el-form-item label="问题类型" prop="type">
          <el-select v-model="issueForm.type" placeholder="请选择问题类型">
            <el-option label="设施损坏" value="设施损坏" />
            <el-option label="卫生问题" value="卫生问题" />
            <el-option label="安全隐患" value="安全隐患" />
            <el-option label="其他" value="其他" />
          </el-select>
        </el-form-item>
        <el-form-item label="优先级" prop="priority">
          <el-select v-model="issueForm.priority" placeholder="请选择优先级">
            <el-option label="高" value="高" />
            <el-option label="中" value="中" />
            <el-option label="低" value="低" />
          </el-select>
        </el-form-item>
        <el-form-item label="问题描述" prop="description">
          <el-input
            v-model="issueForm.description"
            type="textarea"
            :rows="4"
            placeholder="请详细描述您遇到的问题"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showAddIssueDialog = false">取消</el-button>
          <el-button type="primary" @click="submitIssue" :loading="submitting">提交</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import Map from '@arcgis/core/Map'
import MapView from '@arcgis/core/views/MapView'
import FeatureLayer from '@arcgis/core/layers/FeatureLayer'
import Graphic from '@arcgis/core/Graphic'
import gaodeLayer from '@/utils/GaoDeBaseLayer'
import Query from '@arcgis/core/rest/support/Query.js'
import { useAuthStore } from '@/stores/auth'
import type { FormInstance } from 'element-plus'
import { ChatDotRound } from '@element-plus/icons-vue'
import { Picture } from '@element-plus/icons-vue'
import PictureMarkerSymbol from '@arcgis/core/symbols/PictureMarkerSymbol'
import wcIcon from '@/assets/WC.png'

// 定义评论和问题报告的接口
interface Review {
  id: string
  facilityId: string
  facilityName: string
  username: string
  rating: number
  comment: string
  date: string
  cleanliness: number
  facility: number
  convenience: number
  adminReply?: string
}

interface Issue {
  id: string
  facilityId: string
  facilityName: string
  date: string
  reporter_name: string
  type: string
  description: string
  status: string
  priority: string
  adminReply?: string
}

// 获取认证状态
const authStore = useAuthStore()

// 状态变量
const showAttributeDialog = ref(false)
const showAddReviewDialog = ref(false)
const showAddIssueDialog = ref(false)
const submitting = ref(false)
let selectedFeature: Graphic | null = null
const reviews = ref<Review[]>([])
const issues = ref<Issue[]>([])
let bathroomLayer: FeatureLayer | null = null

// 表单引用
const reviewFormRef = ref<FormInstance>()
const issueFormRef = ref<FormInstance>()

// 评论表单
const reviewForm = ref<{
  id: string
  facilityId: string
  facilityName: string
  username: string
  rating: number
  comment: string
  date: string
  cleanliness: number
  facility: number
  convenience: number
  adminReply?: string
}>({
  id: '',
  facilityId: '',
  facilityName: '',
  username: '',
  rating: 0,
  date: '',
  comment: '',
  cleanliness: 0,
  facility: 0,
  convenience: 0,
})

// 问题表单
const issueForm = ref<{
  id: string
  facilityId: string
  facilityName: string
  date: string
  reporter_name: string
  type: string
  description: string
  status: string
  priority: string
  adminReply?: string
}>({
  id: '',
  facilityId: '',
  facilityName: '',
  date: '',
  reporter_name: '',
  type: '',
  status: '待处理',
  description: '',
  priority: '中',
})

// 表单验证规则
const reviewRules = {
  rating: [{ required: true, message: '请选择评分', trigger: 'change' }],
  comment: [{ required: true, message: '请输入评论内容', trigger: 'blur' }],
}

const issueRules = {
  type: [{ required: true, message: '请选择问题类型', trigger: 'change' }],
  description: [{ required: true, message: '请输入问题描述', trigger: 'blur' }],
  priority: [{ required: true, message: '请选择优先级', trigger: 'change' }],
}

// 地图和视图引用
let view: MapView | null = null

onMounted(() => {
  initMap()
})

onUnmounted(() => {
  if (view) {
    view = null
  }
})

// 初始化地图
const initMap = () => {
  try {
    // 创建地图实例
    const map = new Map({
      basemap: {
        baseLayers: [gaodeLayer],
      },
    })

    // 创建地图视图
    view = new MapView({
      container: 'viewDiv',
      map: map,
      center: [116.3, 39.9], // 北京的经纬度
      zoom: 10,
    })

    // 创建卫生间设施要素图层
    bathroomLayer = new FeatureLayer({
      url: 'https://services.arcgis.com/Jaqp8M1tVnnHQ5RM/arcgis/rest/services/Bathroom_FacilitiesManagementSystem/FeatureServer/0',
      outFields: ['*'], // 获取所有字段
      renderer: {
        type: 'simple',
        symbol: new PictureMarkerSymbol({
          url: wcIcon,
          width: 24,
          height: 24
        }),
      },
    })

    // 添加图层到地图
    map.add(bathroomLayer)

    // 添加点击事件
    view.on('click', (event) => {
      // 执行空间查询
      const query = new Query({
        geometry: event.mapPoint, // 获取点击位置
        distance: 100, // 查询半径
        units: 'meters',
        spatialRelationship: 'intersects',
        outFields: ['*'], // 获取所有字段
        returnGeometry: true,
      })

      // 执行查询
      bathroomLayer!
        .queryFeatures(query)
        .then((result) => {
          if (result.features.length > 0) {
            // 获取第一个匹配的要素
            selectedFeature = result.features[0]

            // 解析JSON字符串字段
            try {
              if (selectedFeature.attributes.reviews) {
                reviews.value = JSON.parse(selectedFeature.attributes.reviews)
              } else {
                reviews.value = []
              }

              if (selectedFeature.attributes.issues) {
                issues.value = JSON.parse(selectedFeature.attributes.issues)
              } else {
                issues.value = []
              }
            } catch (error) {
              console.error('解析JSON数据失败:', error)
              reviews.value = []
              issues.value = []
            }

            // 显示属性对话框
            showAttributeDialog.value = true
          } else {
            ElMessage.info('未找到卫生间设施')
          }
        })
        .catch((error) => {
          console.error('查询失败:', error)
          ElMessage.error('查询设施信息失败')
        })
    })
  } catch (error) {
    console.error('初始化地图失败:', error)
    ElMessage.error('初始化地图失败')
  }
}

// 提交评论
const submitReview = async () => {
  if (!reviewFormRef.value) return

  await reviewFormRef.value.validate(async (valid) => {
    if (valid && selectedFeature && bathroomLayer) {
      submitting.value = true
      try {
        // 创建新评论
        const newReview: Review = {
          id: crypto.randomUUID(), // 生成唯一ID
          facilityId: selectedFeature.attributes.OBJECTID || '',
          facilityName: selectedFeature.attributes.name || '',
          username: authStore.username,
          rating: reviewForm.value.rating,
          comment: reviewForm.value.comment,
          date: new Date().toISOString().split('T')[0],
          cleanliness: reviewForm.value.cleanliness,
          facility: reviewForm.value.facility,
          convenience: reviewForm.value.convenience,
        }

        // 添加到评论列表
        const updatedReviews = [...reviews.value, newReview]

        // 克隆选中的要素
        const updatedFeature = selectedFeature.clone()

        // 更新要素属性
        updatedFeature.attributes = {
          ...updatedFeature.attributes,
          reviews: JSON.stringify(updatedReviews),
          OBJECTID: selectedFeature.attributes.OBJECTID, // 保留原始ID
        }

        // 应用编辑
        const results = await bathroomLayer.applyEdits({
          updateFeatures: [updatedFeature],
        })

        if (results.updateFeatureResults.length > 0) {
          ElMessage.success('评论提交成功')
          reviews.value = updatedReviews
          showAddReviewDialog.value = false

          // 重置表单
          reviewForm.value = {
            id: '',
            facilityId: selectedFeature.attributes.OBJECTID || '',
            facilityName: selectedFeature.attributes.name || '',
            username: '',
            rating: 0,
            date: '',
            comment: '',
            cleanliness: 0,
            facility: 0,
            convenience: 0,
          }
        } else {
          ElMessage.error('评论提交失败')
        }
      } catch (error) {
        console.error('提交评论失败:', error)
        ElMessage.error('提交评论失败')
      } finally {
        submitting.value = false
      }
    }
  })
}
// 提交问题
// 提交问题
const submitIssue = async () => {
  if (!issueFormRef.value) return

  await issueFormRef.value.validate(async (valid) => {
    if (valid && selectedFeature && bathroomLayer) {
      submitting.value = true
      try {
        // 创建新问题
        const newIssue: Issue = {
          id: '', // 后端生成或使用UUID
          facilityId: selectedFeature.attributes.OBJECTID || '',
          facilityName: selectedFeature.attributes.name || '',
          date: new Date().toISOString().split('T')[0],
          reporter_name: authStore.username,
          type: issueForm.value.type,
          description: issueForm.value.description,
          status: '待处理',
          priority: issueForm.value.priority,
          adminReply: '',
        }

        // 添加到问题列表
        const updatedIssues = [...issues.value, newIssue]

        // 克隆选中的要素
        const updatedFeature = selectedFeature.clone()

        // 更新要素属性
        updatedFeature.attributes = {
          ...updatedFeature.attributes,
          issues: JSON.stringify(updatedIssues),
          OBJECTID: selectedFeature.attributes.OBJECTID, // 保留原始ID
        }

        // 应用编辑
        const results = await bathroomLayer.applyEdits({
          updateFeatures: [updatedFeature],
        })

        if (results.updateFeatureResults.length > 0) {
          ElMessage.success('问题提交成功')
          issues.value = updatedIssues
          showAddIssueDialog.value = false

          // 重置表单
          issueForm.value = {
            id: '',
            facilityId: '',
            facilityName: '',
            date: '',
            reporter_name: '',
            type: '',
            status: '待处理',
            description: '',
            priority: '中',
            adminReply: '',
          }
        } else {
          ElMessage.error('问题提交失败')
        }
      } catch (error) {
        console.error('提交问题失败:', error)
        ElMessage.error('提交问题失败')
      } finally {
        submitting.value = false
      }
    }
  })
}
</script>

<style scoped>
.map-container {
  width: 100%;
  height: 100%;
  position: relative;
}

.map-view {
  width: 100%;
  height: 100%;
}

.facility-details {
  padding: 10px;
}

.section-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
  margin-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
  padding-bottom: 10px;
}

.section-title h3 {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
  margin: 0;
}

.reviews-section,
.issues-section {
  margin-top: 10px;
  margin-bottom: 20px;
}

.review-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.username {
  font-weight: bold;
  font-size: 14px;
}

.review-content {
  margin-bottom: 10px;
  font-size: 14px;
  line-height: 1.5;
}

.review-details {
  display: flex;
  gap: 8px;
}

.admin-reply {
  margin-top: 10px;
  background-color: #f5f7fa;
  padding: 8px 12px;
  border-radius: 4px;
  border-left: 3px solid #409eff;
}

.admin-reply-header {
  display: flex;
  align-items: center;
  gap: 5px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 5px;
}

.admin-reply-content {
  color: #606266;
  font-size: 14px;
  line-height: 1.5;
}
.facility-photo-section {
  margin: 20px 0;
  text-align: center;

  .el-image {
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  }
}

.image-error {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 200px;
  color: #909399;

  .el-icon {
    font-size: 50px;
    margin-bottom: 10px;
  }
}
</style>
